<template>
  <div class="container">
    <div class="logo">光谷智慧交通</div>
    <div class="tools">
      <el-menu
        class="el-menu-popper-demo"
        mode="horizontal"
        style="width: 1000px"
      >
        <el-menu-item index="1">
          <router-link
            :to="`/homeView/liveRoad`"
            style="text-decoration: none; color: black"
            >实时路况</router-link
          ></el-menu-item
        >

        <el-menu-item index="2" v-if="unitIndex || adminIndex">
          <router-link
            :to="`/homeView/videoMonitor`"
            style="text-decoration: none; color: black"
            >视频监控</router-link
          ></el-menu-item
        >
        <el-menu-item index="3" v-if="unitIndex || adminIndex">
          <router-link
            :to="`/homeView/addEvent`"
            style="text-decoration: none; color: black"
            >事件添加</router-link
          >
        </el-menu-item>
        <el-menu-item index="4" v-if="unitIndex || adminIndex">
          <router-link
            :to="`/homeView/searchEvent`"
            style="text-decoration: none; color: black"
            >事件查询</router-link
          >
        </el-menu-item>
        <el-menu-item index="5" v-if="unitIndex || adminIndex">
          <router-link
            :to="`/homeView/updateEvent`"
            style="text-decoration: none; color: black"
          >
            事件更新</router-link
          >
        </el-menu-item>
        <el-menu-item index="6" v-if="unitIndex || adminIndex">
          <router-link
            :to="`/homeView/publishAnnouncement`"
            style="text-decoration: none; color: black"
            >发布公告</router-link
          >
        </el-menu-item>
        <el-menu-item index="7" v-if="unitIndex || adminIndex">
          <router-link
            :to="`/homeView/roadInfo`"
            style="text-decoration: none; color: black"
            >路况信息</router-link
          >
        </el-menu-item>
        <el-menu-item index="8" v-if="commonIndex">
          <router-link
            :to="`/homeView/viewAnnouncement`"
            style="text-decoration: none; color: black"
            >查看公告</router-link
          >
        </el-menu-item>

        <el-menu-item index="9" v-if="commonIndex">
          <router-link
            :to="`/homeView/reportRoadCondition`"
            style="text-decoration: none; color: black"
            >报告路况</router-link
          >
        </el-menu-item>
        <el-sub-menu index="10">
          <template #title>
            <router-link
              :to="`/homeView/toolBox`"
              style="text-decoration: none; color: black"
              >工具箱</router-link
            >
          </template>
          <el-menu-item
            v-for="item in measureType"
            :key="item.text"
            :index="item.index"
          >
            <router-link
              :to="`/homeView/toolBox/${item.path}`"
              style="text-decoration: none; color: black"
              >{{ item.text }}</router-link
            >
          </el-menu-item>
        </el-sub-menu>
        <el-menu-item index="11" v-if="adminIndex">
          <router-link
            :to="`/homeView/userManage`"
            style="text-decoration: none; color: black"
            >用户管理</router-link
          >
        </el-menu-item>
      </el-menu>
    </div>
    <div class="search">
      <el-input
        v-model="input"
        style="width: 200px"
        placeholder="请输入交通事故查询信息"
      />
      <el-button v-model="msg" @click="accidentSearch">{{ msg }}</el-button>
    </div>
    <div class="user">
      <el-select
        v-model="selectedOption"
        size="default"
        style="width: 140px"
        @change="handleSelectChange"
      >
        <el-option :label="name" :value="name" />
        <el-option label="退出登录" value="退出登录" />
      </el-select>
    </div>
  </div>
</template>

<script setup>
import { h, ref, onMounted, nextTick, watch } from 'vue'
import { useUserStore } from '@/stores/user'
import { storeToRefs } from 'pinia'
import { useMap } from '@/stores/useMap.js'
import { createImageStyle } from '../hooks/eventInfoHook.js'
import router from '../router'
import * as userApi from '@/api/userRequest.js'
let drawLayer, drawSource
const { map } = storeToRefs(useMap())
const { activeIndex, name } = storeToRefs(useUserStore())
const selectedOption = ref('')
const msg = ref('查询')
const flag = ref(false)
const commonIndex = ref(false)
const unitIndex = ref(false)
const adminIndex = ref(true)
const input = ref('')
const { logout: logoutUser } = userApi

const measureType = [
  { text: '测量距离', path: 'distance', index: '10-1' },
  { text: '测量面积', path: 'area', index: '10-2' },
  { text: '关闭测量', path: 'close', index: '10-3' },
  { text: '导出图片', path: 'export', index: '10-4' },
]

const setIndexes = () => {
  if (activeIndex.value === 0) {
    commonIndex.value = true
    unitIndex.value = false
    adminIndex.value = false
  } else if (activeIndex.value === 1) {
    commonIndex.value = false
    unitIndex.value = true
    adminIndex.value = false
  } else {
    commonIndex.value = false
    unitIndex.value = false
    adminIndex.value = true
  }
}

const accidentSearch = () => {
  searchEvent()
  input.value = ''
}
function searchEvent() {
  //初始化查询结构对象，设置查询结构包含几何信息
  var queryStruct = new Zondy.Service.QueryFeatureStruct()
  //是否包含几何图形信息
  queryStruct.IncludeGeometry = true
  //是否包含属性信息
  queryStruct.IncludeAttribute = true
  //是否包含图形显示参数
  queryStruct.IncludeWebGraphic = false
  //实例化查询参数对象
  var queryParam = new Zondy.Service.QueryParameter({
    resultFormat: 'json',
    struct: queryStruct,
  })
  //设置查询分页号
  queryParam.pageIndex = 0
  //设置查询要素数目
  queryParam.recordNumber = 100
  //queryParam.where = name;
  queryParam.where = `事件类型='${input.value}'`
  //实例化地图文档查询服务对象
  var queryService = new Zondy.Service.QueryDocFeature(
    queryParam,
    'guanggu',
    2,
    {
      ip: 'localhost',
      port: '8089', //访问IGServer的端口号，.net版为6163，Java版为8089
    }
  )
  //执行查询操作，querySuccess为查询回调函数
  queryService.query(querySuccess, queryError)
}
function querySuccess(result) {
  drawSource.clear()
  //console.log(result)
  //初始化Zondy.Format.PolygonJSON类
  var format = new Zondy.Format.PolygonJSON()
  //将MapGIS要素JSON反序列化为ol.Feature类型数组
  var features = result.SFEleArray
  features.forEach((feature) => {
    const bound = feature.bound
    if (bound) {
      const centerCoord = [
        (bound.xmin + bound.xmax) / 2,
        (bound.ymin + bound.ymax) / 2,
      ]
      const pointFeature = new ol.Feature({
        geometry: new ol.geom.Point(centerCoord),
        properties: feature,
      })
      pointFeature.setStyle(createImageStyle())
      drawSource.addFeature(pointFeature)
    }
  })
  if (result.TotalCount <= 0) {
    alert('未查询到相关事件')
  }
}
function queryError(error) {
  console.log(error)
}

const handleSelectChange = (value) => {
  if (value === '退出登录') {
    handleLogout(name.value)
  }
}

const handleLogout = async (userName) => {
  try {
    const res = await logoutUser(userName)
    if (res.success) {
      localStorage.removeItem('userName') // 清除本地存储
      router.push({ name: 'login' })
    } else {
      alert('登出失败，请稍后再试')
    }
  } catch (error) {
    console.error('登出失败:', error)
    alert('登出失败，请稍后再试')
  }
}

// 初始化时从 localStorage 中恢复状态
const initializeState = () => {
  const storedUser = JSON.parse(localStorage.getItem('userName'))
  if (storedUser) {
    name.value = storedUser.username
    activeIndex.value = storedUser.roleCode
  }
  setIndexes() // 根据恢复的角色代码设置索引
}
// 监听地图实例
watch(
  () => map.value,
  (newMap) => {
    if (newMap) {
      try {
        map.value.addLayer(drawLayer) // 高亮显示结果
      } catch (error) {
        console.error('初始化地图交互失败:', error)
      }
    }
  },
  { immediate: true }
)
onMounted(async () => {
  initializeState() // 初始化时从localStorage中恢复状态
  await nextTick() // 等待DOM更新
  // console.log(activeIndex.value, name.value);
  selectedOption.value = name.value // 设置初始值为用户名
  drawSource = new ol.source.Vector({
    wrapX: false,
  })
  drawLayer = new ol.layer.Vector({
    source: drawSource,
  })
})
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 6%;
  align-items: center;
  background: white;
  display: flex;
  z-index: 999;
  .logo {
    font-size: 2em;
    font-weight: 600;
    margin-left: 10px;
  }
  .tools {
    .el-menu-popper-demo .el-menu-item {
      border-bottom: none !important; /* 移除下划线 */
      padding: 15px;
    }
    .el-menu--horizontal.el-menu {
      border-bottom: none;
    }
  }
  .search {
    position: absolute;
    right: 160px;
  }
  .user {
    position: absolute;
    right: 10px;
  }
}
</style>
